/*
 * Copyright (c) 2013 WDCY Information Technology Co. Ltd
 * www.wdcy.cc
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * WDCY Information Technology Co. Ltd ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with WDCY Information Technology Co. Ltd.
 */
package com.monkey.web.platform.controller;

import com.monkey.core.domain.permission.Permission;
import com.monkey.core.plugin.dto.MonkeyDto;
import com.monkey.core.repository.search.Searchable;
import com.monkey.core.web.response.MonkeyResponseDto;
import com.monkey.web.dto.request.permission.GrantPermissionRequestDto;
import com.monkey.web.platform.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;

/**
 * @author Wu Tianqiang
 */
@Controller
@RequestMapping(value = "/m", produces = {MediaType.APPLICATION_JSON_VALUE})
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @RequestMapping(value = "/permission", method = RequestMethod.POST)
    public String addPermission(MonkeyDto monkeyDto) {
        monkeyDto.println();
        permissionService.addPermission(monkeyDto);
        return "SUCCESS:新增成功";
    }

    @RequestMapping(value = "/permission", method = RequestMethod.PUT)
    public String modifyPermission(MonkeyDto monkeyDto) {
        monkeyDto.println();
        permissionService.modifyPermission(monkeyDto);
        return "SUCCESS:修改成功";
    }

    @RequestMapping(value = "/permission/{ids}", method = RequestMethod.DELETE)
    public String removePermission(@PathVariable Long[] ids) {
        permissionService.delete(ids);
        return "SUCCESS:删除成功";
    }

    @RequestMapping(value = "/permissions", method = RequestMethod.GET)
    public Page<Permission> permissions(Searchable searchable) {
        searchable.addSort(Sort.Direction.DESC, "createTime");
        return permissionService.findAll(searchable);
    }

    @RequestMapping(value = "/resource/permission/user", method = RequestMethod.POST)
    public MonkeyResponseDto grantPermissionToUser(@Valid GrantPermissionRequestDto grantPermissionRequestDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return new MonkeyResponseDto().fail(bindingResult);
        }
        return permissionService.grantPermissionToUser(grantPermissionRequestDto);
    }

}